from ensembel.decision_tree import *
import numpy as np
from math import log
import random as rd

def random_forest_training(data_train, trees_num):
    '''
    构造随机森林
    :param data_train:训练数据
    :param trees_num: 分类树的个数
    :return: tress_result(list):每一棵树的最好划分
            trees_feature: 每一棵树中对原始特征的选择
    '''
    trees_result = []
    trees_feature = []
    n = np.shape(data_train)[1]
    if n > 2:
        k = int(log(n - 1, 2)) + 1
    else:
        k = 1

    for i in range(trees_num):

        data_samples, feature = choose_samples(data_train, k)

        tree = build_tree(data_samples)

        trees_result.append(tree)
        #TODO
        trees_feature.append(feature)
    return trees_result, trees_feature

def choose_samples(data, k):
    '''
    从样本中随机选择样本及特征
    :param data: 原始数据集
    :param k: 选择特征个树
    :return: date_samples: 被选出来的样本
            feature: 被选出来的特征index
    '''
    m, n = np.shape(data)

    feature = []
    for j in range(k):
        #n-1列是标签
        feature.append(rd.randint(0, n-2))

    index = []
    for i in range(m):
        index.append(rd.randint(0, m-1))

    data_samples = []
    for i in range(m):
        data_tmp = []
        for fea in feature:
            data_tmp.append(data[index[i]][fea])
        data_tmp.append(data[index[i]][-1])
        data_samples.append(data_tmp)
    return data_samples, feature